import React, { useState, useEffect, useContext  } from 'react';
import { Table, Tag, Button, Popconfirm, message,Space, Pagination, Form, Input, Select,DatePicker, Modal, Row, Col, TreeSelect, Radio,Tree   } from 'antd';
import { Link, useLocation, useNavigate} from 'react-router-dom';
import { listUser, addUser, updateUser, resetUserPwd, changeUserStatus, getUser, deptTreeSelect, delUser } from '../../../api/user';
import { DictContext } from '../../../context/context';
import DictTag from '../../../components/DictTag';
import { SearchOutlined , RedoOutlined, PlusOutlined, EditOutlined, DeleteOutlined} from '@ant-design/icons';
function User() {

  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState('');
  const [total, setTotal] = useState(0);
  const [roleOptions, setRoleOptions] = useState([]);
  const [postOptions, setPostOptions] = useState([]);
  const [deptOptions, setDeptOptions] = useState([]);
  const { useDict, addDateRange } = useContext(DictContext);
  const { RangePicker } = DatePicker;
  const [queryParams, setQueryParams] = useState({pageSize:4, pageNum:1});
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [single, setSingle] = useState(true);
  const [multiple, setMultiple] = useState(true);
  const [ids,setIds] = useState([]);
  const { Search } = Input;
  const navigate = useNavigate();

  const { sys_normal_disable,sys_user_sex } = useDict('sys_normal_disable','sys_user_sex');
  
  //console.log('=======sys_normal_disable==',sys_normal_disable);
  //console.log('=======ddd==',useDict('sys_normal_disable'));

  const [form] = Form.useForm();
  const [formAdd] = Form.useForm();
  // useEffect(() => {
  //   getList();
  // },[])

  const [searchValue, setSearchValue] = useState('');

  const onSearch = (e) => {
    setSearchValue(e.target.value);
  };


  const onSelectChange = newSelectedRowKeys => {
    //console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
    setSingle(newSelectedRowKeys.length != 1) ;
    setMultiple(!newSelectedRowKeys.length);
    setIds(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handleUpdate = (row) => {
    //console.log('===handleUpdate==',row);
  //const userId = row.userId || ids.value;
  const userId = row.userId || ids;
  //console.log('===handleUpdate1==',userId, ids);
  getUser(userId).then(response => {
    //form.value = response.data;
    formAdd.setFieldsValue(response.data);
    //console.log('===handleUpdate1==',response);
    setRoleOptions(response.roles.map(item => {
      return {
        value: item.roleId,
        label: item.roleName
      }
    }));
    setPostOptions(response.posts.map(item => {
      return {
        value: item.postId,
        label: item.postName
      }
    }));
    //form.value.postIds = response.postIds;
    //form.value.roleIds = response.roleIds;
    formAdd.setFieldValue('postIds',response.postIds);
    formAdd.setFieldValue('roleIds',response.roleIds);
    setOpen(true);
    setTitle("修改用户");
    //form.password = "";
  });
  }
  
  const handleDelete = (row) => {
    //console.log('===handleDelete==',row);
    const userIds = row?.userId || ids;
    delUser(userIds).then(response => {
      if (response.code === 200) {
        message.success('删除成功');
        getList();
      } else {
        message.error(response.msg);
      }
    })

  }

  const delCancel = () => {
    //message.error('取消删除');
  }


  const columns = [
    {
      title: '用户编号',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName',
    },
      {
        title: '用户昵称',
        dataIndex: 'nickName',
        key: 'nickName',
      },
      {
        title: '性别',
        dataIndex: 'sex',
        key: 'sex',
        render: (text) => {
          return <DictTag dictType="sys_user_sex" value={text} options={sys_user_sex} />
        }
      },
      {
        title: '部门',
        dataIndex: 'deptName',
        key: 'deptName',
        render: (text, record) => {
          return record.dept?.deptName;
        }
      },
      {
        title: '手机号码',
        dataIndex: 'phonenumber',
        key: 'phonenumber',
      },
      {
        title: '用户状态',
        dataIndex: 'status',
        key: 'status',
        render: (text) => {
          if (text === '0') {
            return <Tag color="green">正常</Tag>
          } else {
            return <Tag color="red">停用</Tag>
          }
        }
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
      }
    ,
    {
      title: '操作',
      key: 'action',
      render: (text, record) =>
          <Space size="middle">
          <Button type='link' onClick={() => handleUpdate(record)}>修改</Button>
          <Popconfirm
            title="删除确认"
            description={`是否确认删除用户编号为 ${record.userId} 的数据项？`}
            onConfirm={() => handleDelete(record)}
            onCancel={delCancel}
            okText="确定"
            cancelText="取消"
          >
          <Button type='link'>删除</Button>
          </Popconfirm>
          </Space>
    }
  ];


  useEffect(() => {
    //console.log('Success:', queryParams);
    setLoading(true);
    getList();  
    deptTreeSelect().then(res => {
      setDeptOptions(res.data);
    })
  },[queryParams])

  const onFinish = values => {
    //console.log('===onFinish={onFinish}=====',addDateRange(values, values.timeRange));
    setQueryParams( preState => ({
      ...preState,
      ...values,
    }));
  };

  // 定义一个函数，用于获取列表
  function getList() {
    listUser(addDateRange(queryParams, queryParams.timeRange)).then(res => {
      //console.log(res.rows);
      setData(res.rows);
      setLoading(false);
      setTotal(res.total);
    }).catch(err => {
      console.log('=========user==err',err);
      navigate('/login');
    })
  }

  const reset = () => {
    form.resetFields();
  }

  const handleAdd = () => {
    //console.log('===handleAdd==');
    setOpen(true);
    setTitle('新增用户');
    getUser().then(res => {
      //console.log('===getUser==',res);
      setRoleOptions(res.roles.map(item => {
        return {
          value: item.roleId,
          label: item.roleName
        }
      }));
      setPostOptions(res.posts.map(item => {
        return {
          value: item.postId,
          label: item.postName
        }
      }));
    });

    deptTreeSelect().then(res => {
      setDeptOptions(res.data);
    })
  }

  const handleCancel = () => {
    //console.log('===handleAdd==');
    setOpen(false);
  }

  const handleOk = () => {
    //console.log('===handleOk==', formAdd.getFieldValue());
    if(formAdd.getFieldValue().userId  == undefined){
      addUser(formAdd.getFieldValue()).then(res => {
        message.success('新增成功');
        setOpen(false);
        getList();
      })
    } else {
      updateUser(formAdd.getFieldValue()).then(res => {
        message.success('修改成功');
        setOpen(false);
        getList();
      })
    }
  }

  const onChange = page => {
    setQueryParams( preState => ({
      ...preState,
      pageNum: page.current,
      pageSize: page.pageSize,
    }))
  };

  function handleNodeClick(data) {
    //console.log('===handleNodeClick==',data);
    setQueryParams( preState => ({
      ...preState,
      deptId: data[0]
    }))
  };
  return (
    <div style={{
      height: '100%',
    }}>
      <Row gutter={[16, 16]}>
        <Col span={3}>
        <Search style={{ marginBottom: 8 }} placeholder="请输入部门名称" value={searchValue} onChange={onSearch} />
        <Tree treeData={deptOptions} fieldNames={{ title: 'label', key: 'id', children: 'children' }} filterTreeNode={(node) => node.label.indexOf(searchValue) > -1} defaultExpandAll={true} onSelect={handleNodeClick}/>
      </Col>
      <Col span={21}>
      <Form form={form} layout="inline" onFinish={onFinish} style={{marginBottom: 16,}}>
        <Form.Item label="用户名称" name="userName">
          <Input placeholder='请输入用户名称' allowClear/>
        </Form.Item>
        <Form.Item label="手机号码" name="nickName">
          <Input placeholder='请输入手机号码' allowClear/>
        </Form.Item>
        <Form.Item label="状态" name="status">
          <Select options={sys_normal_disable.value} placeholder="请选择状态" allowClear/>
        </Form.Item>
        <Form.Item label="创建时间" name="timeRange" style={{marginBottom: 16,}}>
          <RangePicker showTime format="YYYY-MM-DD HH:mm:ss"/>
        </Form.Item>
        <Form.Item>
          <Space>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>查询</Button>
          <Button  icon={<RedoOutlined/>} onClick={reset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
      <Space style={{ marginBottom: 16 }}>
      <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>新增</Button>
      <Button color="cyan" variant="solid" icon={<EditOutlined />}  onClick={handleUpdate} disabled={single}>修改</Button>
      <Popconfirm
        title="删除确认"
        description={`是否确认删除用户编号为 的数据项？`}
        onConfirm={() => handleDelete()}
        onCancel={delCancel}
        okText="确定"
        cancelText="取消"
      >
        <Button color="danger" variant="solid" icon={<DeleteOutlined />} disabled={multiple}>删除</Button>
      </Popconfirm>
      </Space>
      <Table loading={loading} rowSelection={rowSelection} dataSource={data} columns={columns} pagination={{ pageSize: queryParams.pageSize, current: queryParams.pageNum ,showQuickJumper: true, pageSizeOptions: [3, 5, 10, 20], showSizeChanger: true, total: total, showTotal: total => `共 ${total} 条`}} rowKey={record => record.userId} onChange={onChange}/>
      </Col>
      </Row>
      {/* <Pagination total={total} showTotal=  {(total) => `共 ${total} 条`} pageSize={3} pageSizeOptions={[3,5,10]} showQuickJumper showSizeChanger /> */}
      <Modal open={open} title={title} onOk={handleOk} onCancel={handleCancel}>
        <Form style={{ marginTop: 30 }} form={formAdd}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="用户昵称" name="nickName">
                <Input placeholder='请输入用户昵称' allowClear/>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="归属部门" name="deptId">
                <TreeSelect treeData={deptOptions} placeholder="请选择归属部门"  fieldNames={{ label: 'label', value: 'id', children: 'children' }} allowClear/>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
          <Col span={12}>
              <Form.Item label="手机号码" name="phonenumber">
                <Input placeholder='请输入手机号码' allowClear/>
              </Form.Item>
            </Col>
            <Col span={12}>
                <Form.Item label="邮箱" name="email">
                  <Input placeholder='请输入邮箱' allowClear/>
                </Form.Item>
              </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="用户名称" name="userName">
                <Input placeholder='请输入用户名称' allowClear/>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="密码" name="password">
                <Input.Password placeholder='请输入密码' allowClear/>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="性别" name="sex">
                <Select options={sys_user_sex.value} placeholder="请选择性别" allowClear/>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="状态" name="status">
                <Radio.Group options={sys_normal_disable.value} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="岗位" name="postIds">
                <Select options={postOptions} placeholder="请选择岗位" mode="multiple" allowClear/>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="角色" name="roleIds">
                <Select options={roleOptions} placeholder="请选择角色" mode="multiple" allowClear/>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item label="备注" name="remark">
                <Input.TextArea placeholder='请输入备注' allowClear/>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
}

export default User;